package com.zking.note.service;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zking.note.exception.NameOrPasswordException;
import com.zking.note.exception.ServiceException;
import com.zking.note.exception.UserExistException;
import com.zking.note.mapper.UserMapper;
import com.zking.note.pojo.User;

/**
 * 业务层实现类
 * 
 * @author Administrator
 */
@Service("userService")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	/**
	 * 登录
	 */
	public User login(String username, String password) throws Exception {
		// 入口参数检查
		if (username == null || username.trim().isEmpty()) {
			throw new NameOrPasswordException("用户名不能为空");
		}
		if (password == null || password.trim().isEmpty()) {
			throw new NameOrPasswordException("密码不能为空"); 
		}
		// 从业务层查询用户信息
		User user = userMapper.findUserByName(username);
		if (user == null) {
			throw new NameOrPasswordException("用户名或者密码错误");
		}
		if (user.getUser_password().equals(password)) {
			return user;// 登录成功
		}
		throw new NameOrPasswordException("用户名或者密码错误");
	}

	/**
	 * 用户注册的方法
	 * 
	 * @param name
	 *            用户名
	 * @param password
	 *            密码
	 * @param nick
	 *            昵称
	 * @return
	 * @throws Exception
	 */
	public User regist(String name, String password, String nick)
			throws Exception {
		String rule = "^\\w{3,10}$";
		if (name == null || name.trim().isEmpty()) {
			throw new ServiceException("用户名不能为空");
		}
		if (!name.matches(rule)) {
			throw new ServiceException("用户名不合格！");
		}
		if (password == null || password.trim().isEmpty()) {
			throw new ServiceException("密码不能为空");
		}
		if (!password.matches(rule)) {
			throw new ServiceException("密码不合格！");
		}
		if (nick == null || nick.trim().isEmpty()) {
			throw new ServiceException("昵称不能为空！");
		}
		rule = "^.{3,10}$";
		if (!nick.matches(rule)) {
			throw new ServiceException("昵称不合格！");
		}
		User user = userMapper.findUserByName(name);
		if (user != null) {
			throw new UserExistException("用户已存在！");
		}
		String id = UUID.randomUUID().toString();
		user = new User(id, name, password, "", nick);
		userMapper.addUser(user);
		// 发送大礼包....
		return user;
	}
}
